import app from '@system.app';
import {getApp} from '../../common.js';

export default {
    data: {
        progress: '',
        desc: '',
        progressStatus: [],
        descStatus: [],
        failDescStatus: [],
        deviceImg: '',
        state: "等待中",
        wifiApInfo: {},
        isFail: false,
        isNAN: true,
        // TODO:
        sessionId: '',
        targetDeviceId: "01234567890123450123456789012345",
        deviceId: ''
    },
    onInit() {
        this.deviceImg = '/common/img/' + getApp(this).Product.productName + ".png";
        this.progressStatus = [
            this.$t('strings.progress-20'),
            this.$t('strings.progress-40'),
            this.$t('strings.progress-60'),
            this.$t('strings.progress-80'),
            this.$t('strings.progress-100'),
        ];
        this.descStatus = [
            this.$t('strings.desc-20'),
            this.$t('strings.desc-40'),
            this.$t('strings.desc-60'),
            this.$t('strings.desc-80'),
            this.$t('strings.desc-100'),
        ];
        this.failDescStatus = [
            this.$t('strings.fail-desc-0'),
            this.$t('strings.fail-desc-20'),
            this.$t('strings.fail-desc-40'),
            this.$t('strings.fail-desc-60'),
            this.$t('strings.fail-desc-80'),
            this.$t('strings.fail-desc-100'),
        ];
        this.progress = this.$t('strings.progress-0');
        this.desc = this.descStatus[0];
//        this.discoverDevice();
//        this.goToControl();     // 测试control模块
        console.info("onInit()");  //test
        this.isNAN = true
        setTimeout(() => {
            this.getWifiInfo();
        }, 100)

    },
//    getWifiInfo() {
//        // Step3 get the WiFi information of the current phone connection.
//        getApp(this).NetConfig.getWifiList((result) => {
//            if (result.code == 0 && result.data && result.data.length > 0) {
//                this.progress = this.progressStatus[3];
//                this.desc = this.descStatus[3];
//                this.configDevice(result.data[0]);
//            } else {
//                this.progress = this.progressStatus[4];
//                this.desc = this.descStatus[3];
//                this.disconnectDevice();
//            }
//        });
//    },
    getWifiInfo() {
        this.desc = '开始获取wifi列表'
        console.info("开始获取wifi列表");  //test
        getApp(this).NetConfig.getWifiList((result) => {
            if (result.code == 0 && result.data && result.data.length > 0) {
                this.desc = '获取wifi列表成功'
                console.info("获取wifi列表成功");  //test
                this.wifiApInfo = result.data[0]
                for (let i = 0;i < result.data.length; i++) {
                    if (result.data[i].hasDefaultPassword) {
                        this.wifiApInfo = result.data[i];
                        break;
                    }
                }
                if (Object.keys(this.wifiApInfo).length == 0) {
                    this.desc = "没有已连上的wifi"
                    console.info("没有已连上的wifi");  //test
                    return;
                }
                if (this.isNAN) {
                    this.discoverDeviceByNAN()
                } else {
                    this.startSoftAp()
                }
            } else {
                this.desc = "获取wifi列表失败"
                console.info("获取wifi列表失败");  //test
                this.isFail = true
            }
        });
    },
    //    discoverDevice() {
    //        let scanInfo = {
    //            duration: 30,
    //            lockTime: 60,
    //            sessionId: getApp(this).ConfigParams.sessionId
    //        };
    //        // Step1 discover the device through the NaN broadcast service.
    //        getApp(this).NetConfig.discoveryByNAN(scanInfo, (result) => {
    //            if (result.code == 0) {
    //                this.progress = this.progressStatus[1];
    //                this.desc = this.descStatus[1];
    //                getApp(this).ConfigParams.deviceInfo = result.data;
    //                this.registerDisconnectCallback(getApp(this).ConfigParams.deviceInfo.sessionId);
    //                this.connectDevice();
    //            } else {
    //                this.progress = this.progressStatus[4];
    //                this.desc = this.failDescStatus[1];
    //                this.disconnectDevice();
    //            }
    //        });
    //    },
    discoverDeviceByNAN() {
        this.desc = "开始发现设备"
        let scanInfo = {
            duration: 5,
            lockTime: 60,
            sessionId: getApp(this).ConfigParams.sessionId
        };
        // Step1 discover the device through the NaN broadcast service.
        getApp(this).NetConfig.discoveryByNAN(scanInfo, (result) => {
            if (result.code == 0) {
                this.desc = "NAN发现设备成功"
                getApp(this).ConfigParams.deviceInfo = result.data;
                this.registerDisconnectCallback(getApp(this).ConfigParams.deviceInfo.sessionId);
                let connectInfo = {
                    targetDeviceId: getApp(this).ConfigParams.deviceInfo.productId,
                    type: 0,
                    pin: '11111111',
                    password: getApp(this).ConfigParams.deviceInfo.sn,
                    sessionId: getApp(this).ConfigParams.deviceInfo.sessionId
                };
                console.info("netconfig connectInfo" + JSON.stringify(connectInfo))
                this.connectDevice(connectInfo);
            } else {
                this.desc = "NAN发现设备失败"
                this.startSoftAp()
            }
        });
    },
    startSoftAp() {
        this.isNAN = false
        this.desc = "softAP配网"
        this.disconnectDevice()
        getApp(this).ConfigParams.deviceInfo.sessionId = ''
        this.discoverDeviceBySoftAp()
    },
    discoverDeviceBySoftAp() {
        if (!this.targetDeviceId) {
            this.desc = "apName为空: " + this.targetDeviceId  //TODO
            return;
        }
        getApp(this).NetConfig.discoveryBySoftAp((result) => {
            console.info("NetConfig# discoveryBySoftAp" + JSON.stringify(result))
            if (result.code == 0) {
                this.desc = "softAP发现成功"
                getApp(this).ConfigParams.deviceInfo = result.data;
                getApp(this).ConfigParams.deviceInfo.sessionId = ''
                let connectInfo = {
                    targetDeviceId: "teamX-Lamp01",
                    // targetDeviceId: this.targetDeviceId, // 设备ap热点名，从NFC中tag=5的值获取
                    type: 1,
                    pin: '11111111',
                    password: '',
                    sessionId: ''
                };
                this.connectDevice(connectInfo);
            } else {
                this.isFail = true
            }
        })
    },
//    async configDevice(wifiApInfo) {
//        let netConfigInfo = {
//            ssid: wifiApInfo.ssid,
//            ssidPassword: '',
//            isDefaultPassword: true,
//            channel: wifiApInfo.channel,
//            sessionId: getApp(this).ConfigParams.deviceInfo.sessionId,
//            type: 0,
//            wifiApId: wifiApInfo.wifiApId,
//            vendorData: '',
//            timeout: 30,
//            paramValid: true
//        };
//        // Step4 config the device net.
//        getApp(this).NetConfig.configDeviceNet('deviceInfo', 'accountInfo', netConfigInfo, (result) => {
//            if (result.code == 0) {
//                this.progress = this.progressStatus[4];
//                this.desc = this.descStatus[4];
//                this.registerMsgReceive()
//                // Step5 config the device net success, go to the control.
//                this.goToControl();
//            } else {
//                this.progress = this.progressStatus[4];
//                this.desc = this.failDescStatus[4];
//                this.disconnectDevice();
//            }
//        });
//    },
    //    connectDevice() {
    //        let connectInfo = {
    //            targetDeviceId: getApp(this).ConfigParams.deviceInfo.productId,
    //            type: 0,
    //            pin: '0123456789012345',
    //            password: getApp(this).ConfigParams.deviceInfo.sn,
    //            sessionId: getApp(this).ConfigParams.deviceInfo.sessionId
    //        };
    //        // Step2 connect the device.
    //        getApp(this).NetConfig.connectDevice(connectInfo, (result) => {
    //            if (result.code === 0) {
    //                this.progress = this.progressStatus[2];
    //                this.desc = this.descStatus[2];
    //                this.getWifiInfo();
    //            } else {
    //                this.progress = this.progressStatus[4];
    //                this.desc = this.failDescStatus[2];
    //                this.disconnectDevice();
    //            }
    //        });
    //    },
    connectDevice(connectInfo) {
        if (this.isNAN) {
            this.desc = "连接设备中(NAN)"
        } else {
            this.desc = "连接设备中(SoftAp)"
        }
        console.info("Netconfig connectDevice argument" + JSON.stringify(connectInfo))
        // Step2 connect the device.
        getApp(this).NetConfig.connectDevice(connectInfo, (result) => {
            if (result.code === 0) {
                this.desc = "连接设备成功"
                this.configDevice();
            } else {
                console.error("netconfig connectDevice fail" + JSON.stringify(result))
                if (this.isNAN) {
                    this.desc = "连接设备失败(NAN)"
                    this.startSoftAp()
                } else {
                    this.desc = "连接设备失败(softAp)"
                    this.isFail = true
                    this.disconnectDevice();
                }
            }
        });
    },
    async configDevice() {
        this.desc = "开始配网"
        let netConfigInfo = {
            ssid: this.wifiApInfo.ssid,
            ssidPassword: '',
            isDefaultPassword: true,
            channel: this.wifiApInfo.channel,
            sessionId: getApp(this).ConfigParams.deviceInfo.sessionId,
            type: this.isNAN ? 0 : 1,
            wifiApId: this.wifiApInfo.wifiApId,
            vendorData: '',
            timeout: 30,
            paramValid: true
        };
        console.info("netconfig configDevice" + JSON.stringify(netConfigInfo))
        // Step4 config the device net.
        getApp(this).NetConfig.configDeviceNet('deviceInfo', 'accountInfo', netConfigInfo, (result) => {
            if (result.code == 0) {
                this.desc = "配网成功"
                // Step5 config the device net success, go to the control.
                this.goToControl();
            } else if (this.isNAN) {
                this.startSoftAp()
            } else {
                this.desc = "配网失败"
                this.isFail = true
                this.disconnectDevice();
            }
        });
    },
    registerDisconnectCallback(sessionId) {
        let commonInfo = {
            sessionId: sessionId
        }
        getApp(this).NetConfig.registerDisconnectCallback(commonInfo, (result) => {
            if (result.code == 0) {
                this.desc = this.failDescStatus[5];
            }
        });
    },
    registerMsgReceive() {
        let commonInfo = {
            sessionId: getApp(this).ConfigParams.deviceInfo.sessionId
        }
        getApp(this).NetConfig.registerMsgReceive(commonInfo, () => {
        });
    },
    disconnectDevice() {
        let commonInfo = {
            sessionId: getApp(this).ConfigParams.deviceInfo.sessionId
        }
        getApp(this).NetConfig.disconnectDevice(commonInfo, (result) => {
            if (result.code == 0) {
                return;
            }
        });
    },
    goToControl() {
        this.desc = "配网成功,准备跳转至设备控制页面"
        this.disconnectDevice();
        let target = {
            bundleName: 'com.zml.solarcontrol.hmservice',
            abilityName: 'com.zml.control.ControlMainAbility',
            data: {
                session_id: getApp(this).ConfigParams.deviceInfo.sessionId,
                product_id: getApp(this).Product.productId,
                product_name: getApp(this).Product.productName
            }
        }
        FeatureAbility.startAbility(target);
        app.terminate()
    },
    cancel() {
        app.terminate();
    }
}